<?php
class TW_Database extends PDO {

    public function __construct($DB_TYPE, $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS) {
        parent::__construct($DB_TYPE . ':host=' . $DB_HOST . ';dbname=' . $DB_NAME . ';charset=utf8', $DB_USER, $DB_PASS);
    }

    public function select($sql, $where = array(), $all = true, $fetchMode = PDO::FETCH_ASSOC) {
        
        $sth = $this->prepare($sql);

        foreach($where as $key => $value) {
            $type = (is_int($value)) ? PDO::PARAM_INT : PDO::PARAM_STR;
            $sth->bindValue("$key", $value, $type);
        }

        $sth->execute();

        if($all) {
            return $sth->fetchAll($fetchMode);
        }
        else {
            return $sth->fetch($fetchMode);
        }

    }

    public function insert($table, $data) {
        ksort($data);

        $fieldNames  = implode('`, `', array_keys($data));
        $fieldValues = ':' . implode(', :', array_keys($data));

        $sth = $this->prepare("INSERT INTO $table (`{$fieldNames}`) VALUES ({$fieldValues})");

        foreach($data as $key => $value) {
            $type = (is_int($value)) ? PDO::PARAM_INT : PDO::PARAM_STR;
            $sth->bindValue(":$key", $value, $type);
        }

        return $this->lastInsertId();

    }

    public function update($table, $data, $where) {
        ksort($data);

        $newData = null;

        foreach($data as $key => $value) {
            $newData .= "`$key`=:$key,";
        }

        $newData = rtrim($newData, ',');

        $sth = $this->prepare("UPDATE $table SET $newData WHERE $where");

        foreach($data as $key => $value) {
            $type = (is_int($value)) ? PDO::PARAM_INT : PDO::PARAM_STR;
            $sth->bindValue(":$key", $value, $key);
        }

        return $sth->execute();

    }

    public function delete($table, $where, $limit = 1) {
        return $this->exec("DELETE FROM $table WHERE $where LIMIT $limit");
    }

}